package com.gcsoftware.web.threads;

import com.alibaba.fastjson.JSONObject;
import com.gcsoftware.gw.TokenInfo;
import com.gcsoftware.utils.SpringContextUtils;
import com.gcsoftware.utils.TokenUtils;
import com.gcsoftware.web.service.FileUploadService;
import org.apache.commons.lang3.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;

/**
 * Created by qs on 2018/4/9.
 */
@Component
public class TokenThread extends Thread {
    private static volatile Queue<TokenInfo> tokenQue;

    public static final String TOKEN_ROLE_PREFIX = "TOKEN_FOR_ROLE_";

    private static RedisTemplate<String, String> redis;

    @Autowired
    @Qualifier("stringRedisTemplate")
    public void setRedis(RedisTemplate redis) {
        TokenThread.redis = redis;
    }


    private static Queue<TokenInfo> initTokenQueue () {
        if (null == tokenQue) {
            synchronized (TokenThread.class) {
                if (null == tokenQue) {
                    tokenQue = new LinkedList<TokenInfo>();
                }
            }
        }
        return tokenQue;
    }

    public static void setTokenQue(final TokenInfo tokenInfo) {
        initTokenQueue().offer(tokenInfo);
    }

    @Override
    public void run() {
        System.out.println("Start token thread...");
        TokenInfo tokenInfo = null;
        while (true) {
            if (null != this.initTokenQueue() && this.initTokenQueue().size() > 0) {
                tokenInfo = this.initTokenQueue().poll();

                try {
                    //redis.boundValueOps(TOKEN_ROLE_PREFIX + tokenInfo.getToken()).set(getStringFrmInfo(tokenInfo), 7200);
                    redis.opsForValue().set(TOKEN_ROLE_PREFIX + tokenInfo.getToken(),getStringFrmInfo(tokenInfo),7200, TimeUnit.SECONDS);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    continue;
                }
            }
        }
    }

    private static String getStringFrmInfo(TokenInfo info) {
        String jsonStr =  JSONObject.toJSONString(info);
        System.out.println(jsonStr);
        return jsonStr;
//        return "{token:"+info.getToken()+",appId:"+info.getAppId()+",appName:" + info.getAppName()+",roleId:"+info.getRoleId()+( null != info.getAppIps() ? ",appIps:" + info.getAppIps().toArray(new String[info.getAppIps().size()]): "") + "}";
    }
}
